package com.xnchat.pro.controller;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.xnchat.pro.dto.HouseChange;
import com.xnchat.pro.enums.ROOMENUM;
import com.xnchat.pro.mapper.HouseChangeRepository;
import com.xnchat.pro.utils.NormalReturn;
import com.xnchat.pro.vo.QfRequest;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PostConstruct;
import java.io.Serializable;
import java.util.*;

/**
 * @author 小凝
 */
@RestController
@RequestMapping("/qiangfang")
public class DoOtherController {


    @Autowired
    HouseChangeRepository houseChangeRepository;
    private final static Map<Integer,String> ROOM_LIST =new HashMap<>();
//http://localhost/qiangfang/dotest?server=1042,1043,1044,1045,1060,1076,1081,1106,1113,1121,1166,1167,1169,1170,1171,1172,1173,1174,1175,1176,1177,1178,1179
    @ResponseBody
    @GetMapping("/jiankong")
    public NormalReturn qf(@RequestBody QfRequest qfRequest) {
        Optional<QfRequest> qfOptional = Optional
                .ofNullable(qfRequest)
                .filter(f -> f.getServer() != null && f.getServerKey() != null);
        if (!qfOptional.isPresent()) {
            return NormalReturn.FAIL.addMessage("参数错误");
        }
        HttpResponse execute = HttpRequest.get("http://wh.nyao.xyz/state/1076").disableCookie().execute();
        String body = execute.body();
        //1076
        HttpResponse response = HttpRequest.get("http://wh.nyao.xyz/api/state/?server=" + qfRequest.getServer() + "&type=0").cookie("api-version=1; sessionid=23z7zc5ipzu0zctf1ust930b0715tmtl").execute();
        Optional<String> value = getValue(response);
        if (!value.isPresent()) {
            return NormalReturn.FAIL.addMessage("消息获取失败");
        }
        ResultMessage resultMessage = JSON.parseObject(value.get(), ResultMessage.class);
        List<Changes> changes = resultMessage.getChanges();
        Specification<HouseChange> specification = (Specification<HouseChange>) (root, query, builder) ->
                builder.equal(root.get("server"), qfRequest.getServer());
        List<HouseChange> recordTime = houseChangeRepository.findAll(specification, PageRequest.of(0, 1, Sort.by(Sort.Direction.DESC, "recordTime")));
        Long lastTime;
        if (recordTime.size() > 0) {
            HouseChange houseChange = recordTime.get(0);
            lastTime = houseChange.getRecordTime();
        }else {
            lastTime=0L;
        }
        List<OnSale> onsale = resultMessage.getOnsale();
        onsale.forEach(q->{
            if(q.getPrice()>10000000&&q.getServer().equals(1076)){
                Integer territoryId = q.getTerritory_id();
                String chengshi="";
                //340->森都 341->沙  641->白银 海->339
                switch (territoryId){
                    case  340:
                        chengshi="森";
                        break;
                    case 241:
                        chengshi="沙";
                        break;
                    case 641:
                        chengshi="白银";
                        break;
                    case 339:
                        chengshi="海";
                        break;
                    default:
                        chengshi="未知，请登陆 http://wh.nyao.xyz/state/1076 查看";
                }
                String desp="房子在:"+chengshi+"\r\n"+(q.getWard_id()+1)+"-"+(q.getHouse_id()+1);
                String title="出房子了！";
                sendMessage("SCT9049Tn45ic46kEeThsKAZLhB0bt5E",title,desp);
            }
        });
        for (Changes change : changes) {
            if(change.getRecord_time()<lastTime){
                continue;
            }
            HouseChange houseChange = new HouseChange();
            houseChange.setHouseId(change.getHouse().getHouse_id());
            houseChange.setRecordTime(change.getRecord_time());
            houseChange.setServer(change.getHouse().getServer());
            houseChange.setTerritoryId(change.getHouse().getTerritory_id());
            houseChange.setWardId(change.getHouse().getWard_id());
            houseChange.setParamA(change.getParam1());
            houseChange.setParamB(change.getParam2());
            houseChange.setType(change.getEvent_type());
            houseChangeRepository.save(houseChange);
        }

        System.out.println(resultMessage);
        return NormalReturn.SUCCESS;
    }

    private Optional<String> getValue(HttpResponse response) {
        return Optional.ofNullable(response).filter(f -> f.getStatus() == 200).map(HttpResponse::body);

    }


    //1076
    @GetMapping("/dotest")
    @ResponseBody
    public NormalReturn doTest(String server) throws InterruptedException {
        String[] s = server.split(",");
        List<String> strings = Arrays.asList(s);
        strings.removeIf(q->ROOM_LIST.get(Integer.valueOf(q))==null);
        int i=0;
        while(i<9999){
            strings.forEach(f->{
                QfRequest re = new QfRequest();
                re.setServer(f);
                re.setServerKey("SCT9049Tn45ic46kEeThsKAZLhB0bt5E");
                qf(re);
            });
            Thread.sleep(3600*1000);
        }


        return NormalReturn.SUCCESS;
    }

    private static void sendMessage(String key,String title,String msg){
        String url="https://sctapi.ftqq.com/"+key+".send";
        Map<String,Object> values =new HashMap<>();
        values.put("title",title);
        values.put("desp",msg);
        HttpUtil.post(url,values);
    }

    public static void main(String[] args) {
        sendMessage("SCT9049Tn45ic46kEeThsKAZLhB0bt5E","抢房测试","正文测试");
    }
    @PostConstruct
    public void init(){
        ROOMENUM[] values = ROOMENUM.values();
        List<ROOMENUM> room = Arrays.asList(values);
        room.forEach(r->
                ROOM_LIST.put(r.getCode(),r.getValue())
        );
    }
}



@Data
class ResultMessage implements Serializable {
    private Integer code;
    private String msg;
    private List<OnSale> onsale;
    private List<Changes> changes;
    private Long last_update;
}

@Data
class OnSale {
    private Integer server;//1076->白金
    private Integer territory_id;// 340->森都 341->沙  641->白银 海->339
    private Integer ward_id;//房区-1
    private Integer house_id;//房间号-1
    private Integer price;//房价
    private Long start_sell;//更新时间
    private Integer size;// 1 s 2 m 3 l
    private String owner;//谁的房子
}

/**
 * event_type
 * 被 param1 购入 历时param2 sold
 * 以 param2 开始售出（前持有人 param1 ） 。 start_selling
 * 持有者从 param1 变更为 param2。change_owner
 * 从 param1 降价到 param2。 price_reduce
 */
@Data
class Changes {
    private House house;//
    private String event_type; //change_owner  start_selling sold(卖出！) price_reduce
    private String param1;
    private String param2;
    private Long record_time;
}

@Data
class House {
    private Integer server;
    private Integer territory_id;
    private Integer ward_id;
    private Integer house_id;
}